<template>
  <div>
    <Card>
      <div class="p-relative">
        <div @click="reset" class="p-absolute refresh-btn">
          <Icon size='24' type="md-refresh" />
        </div>
        <div class="flex-box search-area">
          <div class="flex-item search-btn" @click="create()">
            <Button type="primary">添加</Button>
          </div>
          <div class="flex-item">
            <Input v-model="initConfig.searchObj.mobile" placeholder="请输入手机号"></Input>
          </div>
          <div class="flex-item search-btn" @click="search">
            <Button type="primary">搜索</Button>
          </div>
          <div class="flex-item search-btn" @click="reset">
            <Button>重置</Button>
          </div>

        </div>
      </div>
      <Table :columns="tableOption" :data="data.list" border
        :no-data-text="initConfig.loadingText ? initConfig.loadingText : '暂无数据'" border ref="tables" editable
        search-place="top">
        <template slot-scope="{ row, index }" slot="action">
          <div class="flex-box flex-center flex-margin">
            <Button type='primary' @click="setInfo(row, index)" size='small'>设置</Button>
            <Button type='primary' @click="edit(row, index)" size='small'>修改</Button>
            <Button type='error' @click="del(row, index)" size='small'>删除</Button>
          </div>
        </template>
      </Table>
      <Page class="foot-page" :current='initConfig.page.current' :total="initConfig.page.total"
        :page-size="initConfig.page.pageSize" show-total show-elevator @on-change="changepage"></Page>
    </Card>
    <!-- 添加弹窗 -->
    <Modal v-model="initConfig.createModal" :title="initConfig.createTitle" width='900'>
      <Form ref="form" :model="initConfig.form" :rules="ruleValidate" :label-width="80">
     <!--  <FormItem label="类型"  >
         <RadioGroup v-model="initConfig.form.type">
                <Radio label="1">球馆商家</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
                <Radio label="2">机构</Radio>

            </RadioGroup>
        </FormItem> -->
        <FormItem label="名称" prop="company_name">
          <Input v-model="initConfig.form.company_name" placeholder="请输入公司名称"></Input>
        </FormItem>
        <FormItem label="手机号" prop="mobile" >
          <Input v-model="initConfig.form.mobile" placeholder="请输入手机号"></Input>
        </FormItem>
        <FormItem label="密码"  prop="pwd">
          <Input v-model="initConfig.form.pwd" type="password" placeholder="请输入密码"></Input>
        </FormItem>
        <FormItem label="商户小程序Appid" prop="appId" >
          <Input v-model="initConfig.form.appid" placeholder="请输入商户渠道标记  如：on（瓯宁）"></Input>
        </FormItem>
        <FormItem label="商户渠道标记" prop="business_code" >
          <Input v-model="initConfig.form.business_code" placeholder="请输入商户渠道标记  如：on（瓯宁）"></Input>
        </FormItem>
        <FormItem label="采购账号" prop="tel" >
          <Input v-model="initConfig.form.tel" placeholder="请输入手机号 注：修改密码是接收验证码"></Input>
        </FormItem>
        <FormItem label="支付密码"  prop="pay_password">
          <Input v-model="initConfig.form.pay_password"    type="password" placeholder="请输入密码,长度限制为6位数字组成的交易密码"></Input>
        </FormItem>
        <!-- <FormItem label="确认支付密码"  prop="repay_password">
          <Input v-model="initConfig.form.repay_password"    type="password" placeholder="请输入密码,长度限制为6位数字组成的交易密码，"></Input>
        </FormItem> -->

<!--
        <FormItem  label="平台费率" prop="rate" >
          <Input v-model="initConfig.form.rate"  placeholder="请输入平台费率,例:0.1"></Input>
        </FormItem> -->
      <!--   <FormItem  label="球场折扣" prop="rebate"  >
          <Input v-model="initConfig.form.rebate"  placeholder="请输入球场折扣,例:0.1"></Input>
        </FormItem> -->
        <FormItem label="省市区" prop='province'>
          <Cascader :data="areaData" v-model="initConfig.province" @on-change="changeAreaData"></Cascader>

        </FormItem>
        <FormItem label="详细地址" prop='address'>
          <Input v-model="initConfig.form.address" placeholder="请输入地址"></Input>
        </FormItem>

        <FormItem label="地图设置" class='mapFormItem'>
          <div class='flex-start-box'>
            <Input v-model="initConfig.form.lat" placeholder="lat" style='width: 100px;margin-right: 10px;'></Input>
            <Input v-model="initConfig.form.lng" placeholder="lng" style='width: 100px;margin-right: 10px;'></Input>
            <Button type="primary" @click='setMap'>设置</Button>
          </div>

        </FormItem>
        <FormItem label="状态"  >
         <RadioGroup v-model="initConfig.form.estate">
                <Radio label="1">启用</Radio>&nbsp;&nbsp;&nbsp;&nbsp;
                <Radio label="0">禁用</Radio>

            </RadioGroup>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="primary" @click="save('form')" :disabled="initConfig.isDisable"
          :loading="initConfig.isLoading">保存</Button>
      </div>
    </Modal>
    <!-- 删除弹窗 -->
    <Modal v-model="initConfig.delModal" width="250" title="提示">
      <p class="font16">
        <Icon class='del-tips-icon' type="ios-alert-outline" color='orange' size='22' />确定删除数据？
      </p>
      <div slot="footer">
        <Button @click='initConfig.delModal=false'>取消</Button>
        <Button type="primary" @click='confirmDel'>确定</Button>
      </div>
    </Modal>

    <!-- 地图  -->
    <Modal v-model="showMapModel" title="地图" @on-ok="comfirmUpdateMap" @on-cancel="cancelUpdateMap"
      class-name="show-model" width="1200">
      <div class="outer-box" id="outer-box">
        <Row :gutter="16">
          <i-col span="12">
            <Row :gutter="12">
              <i-col span="6">
                <i-input v-model="data.lat" placeholder="lat"></i-input>
              </i-col>
              <i-col span="6">
                <i-input v-model="data.lng" placeholder="lng"></i-input>
              </i-col>
            </Row>
          </i-col>
        </Row>

        <div id="container" class="map" tabindex="0"></div>
        <div id="panel" class="scrollbar1">
          <div id="searchBar">
            <input id="searchInput" placeholder="输入关键字搜素POI" />
          </div>
          <div id="searchResults"></div>
        </div>
      </div>
      <div slot="footer">
        <Button @click='showMapModel=false'>取消</Button>
        <Button type="primary" @click='selectLocation'>确定</Button>
      </div>

    </Modal>

    <Modal v-model="setInfoModal" width="500" title="设置">
        <div>
            <div>
                <div>
                    基础信息
                </div>
                <template>
                    <Row>
                        <Col span="8">商户</Col>
                        <Col span="16">
                             {{business.company_name}}

                        </Col>
                    </Row>
                    <Row>
                        <Col span="8">商户充值金额</Col>
                        <Col span="16">
                             {{businessCard.balance||0}}

                        </Col>
                    </Row>
                    <Row>
                        <Col span="8">商户额度</Col>
                        <Col span="16">
                             {{businessCard.give_amount||0}}

                        </Col>
                    </Row>
                </template>
            </div>
            <template>
                <Row>
                    <Col span="8">方式</Col>
                    <Col span="16">
                         <Radio-group v-model="type">
                            <Radio label="1">扣除</Radio>
                            <Radio label="2">增加</Radio>

                        </Radio-group>

                    </Col>
                </Row>
                <Row>
                    <Col span="8">充值金额</Col>
                    <Col span="16">
                          <Input v-model="amount" placeholder="请输入金额" style="width: 300px"></Input>

                    </Col>
                </Row>
                <Row>
                    <Col span="8">额度</Col>
                    <Col span="16">
                          <Input v-model="give_amount" placeholder="请输入额度" style="width: 300px"></Input>

                    </Col>
                </Row>
                 <Row>
                    <Col span="8">备注</Col>
                    <Col span="16">
                          <Input v-model="remark" type="textarea" placeholder="请输入备注，最长字数200" style="width: 300px" ></Input>

                    </Col>
                </Row>
            </template>
      </div>
      <div slot="footer">
        <Button @click='setInfoModal=false'>取消</Button>
        <Button type="primary" @click='setBusiness'>确定</Button>
      </div>
    </Modal>

  </div>
</template>
<!-- 公共弹框，成功，失败，报错，loading -->
<script>
  import {
    mapState
  } from 'vuex'
  //  import AMap from AMap
  import {
    permission
  } from '@/config/permission.js'
  import {
    tableOption
  } from '../../../data/users-group/business-list.js'
  // 接口
  import {
    getList,
    insertEnter,
    updateEnter,
    deleteEnter,
    getBusinessInfo,
    setBusinessInfo
  } from '@/api/users-group/business-list.js'
  import {
    initConfig
  } from '@/config/global.js'
  import Tables from '_c/tables'
  import areaData from '@/config/city.js'
  export default {
    name: 'tables_page',
    components: {
      Tables
    },
    created() {
      let _this = this
      this.getList()
    },
    watch: {

    },
    mounted() {

    },
    computed: {
      ...mapState({
        roles: state => state.user.roles
      })
    },
    data() {
      return {
        showMapModel: false,
        initConfig: initConfig,
        tableOption: tableOption,
        areaData: areaData.area,
        setInfoModal:false,
        isAdd: true,

        // 设置
        type:'2',
        amount:'0',
        give_amount:'0',
        remark:'',


        business:{},
        businessCard:{},
        data: {
          list: [],
          lat:'',
          lng:'',
          address:''
        },
        organList:[],
        ruleValidate: {
          company_name: [{
            required: true,
            message: '请输入公司名称',
            trigger: 'blur'
          }],
          mobile: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }],

          pwd: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'
          }],
          tel: [{
            required: true,
            message: '请输入手机号',
            trigger: 'blur'
          }
          ],
          pay_password: [{
            required: true,
            message: '请输入密码',
            trigger: 'blur'

          }
          ],

          address: [{
            required: true,
            message: '请输入详细地址',
            trigger: 'blur'
          }],
          rate:[
            {
            required: true,
            message: '请输入商家费率',
            trigger: 'blur'
            },
            {
            type:'string',
            message: '商家费率为正浮点',
            pattern:'^(1|0)?(?:\\.\\d+)?$',
            trigger: 'blur'
            }
          ],
          rebate:[
            {
            required: true,
            message: '请输入球场折扣',
            trigger: 'blur'
            },
            {
            type:'string',
            message: '球场折扣为正浮点',
            pattern:'^(1|0)?(?:\\.\\d+)?$',
            trigger: 'blur'
            }
          ]

        }
      }
    },
    methods: {
      // 列表数据  rebate
      getList() {
        let _this = this
        let params = {
          page: this.initConfig.page.current,
          size: this.initConfig.page.size,
          mobile: initConfig.searchObj.mobile
        }
        getList(params).then(res => {
          if (res.data.status == 1) {
            let result = res.data.data
            _this.data.list = result.list
            _this.initConfig.page.total = result.total
            _this.organList = result.organList
          } else {
            _this.$Message.error(res.data.message || res.data.msg)
          }
        }).catch(function(error) {
          // 异常
          console.log(error)
        })
      },
      setInfo(row,index){
            let _this = this;
            this.business  = row;
             let param = {
                id:row.id
             };
              getBusinessInfo(param).then(res => {
                console.log(res)
                if (res.data.status == 1) {

                    _this.setInfoModal = true
                    _this.businessCard = res.data.data.businessInfo
                } else {
                  // _this.initConfig.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                // _this.initConfig.createModal = false
                console.log(error)
              })
      },
    setBusiness(){
        let _this = this;
        let param = {
            id: this.business.id,
            type:_this.type,
            amount:_this.amount,
            give_amount:_this.give_amount,
            remark:_this.remark,
         };
        setBusinessInfo(param).then(res => {
            if (res.data.status == 1) {
                _this.setInfoModal = false
                _this.buisnessCard = res.data.data.businessInfo
            } else {
              // _this.initConfig.createModal = false
              // axios响应拦截
            }
        }).catch(function(error) {
            // 异常
            // _this.initConfig.createModal = false
            console.log(error)
        })
      },
      save(name) {
        let _this = this;

        this.$refs[name].validate((valid) => {

          if (valid) {
            if (_this.isAdd) {

              let param = this.initConfig.form;





              insertEnter(param).then(res => {
                if (res.data.status == 1) {
                  _this.initConfig.createModal = false
                  _this.$Message.success('操作成功')
                  _this.getList() // 重新刷新数据
                } else {
                  console.log(res)
                  // _this.initConfig.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                // _this.initConfig.createModal = false
                console.log(error)
              })
            } else {
              let param = this.initConfig.form;
              updateEnter(param).then(res => {
                if (res.data.status == 1) {
                  _this.initConfig.createModal = false
                  _this.$Message.success('操作成功')
                  _this.getList() // 重新刷新数据
                } else {
                  // _this.initConfig.createModal = false
                  // axios响应拦截
                }
              }).catch(function(error) {
                // 异常
                // _this.initConfig.createModal = false
                console.log(error)
              })
            }
          } else {
            this.$Message.error('请输入必填项!');
          }

        })
      },
      // 重置
      reset() {
        this.initConfig.searchObj = {} // 清空搜索框
        this.getList()
      },
      // 查询
      search() {
        this.getList()
      },
      create() {
        this.initConfig.createModal = true
        this.initConfig.createTitle = '商家账号添加'
        this.isAdd = true
        this.initConfig.form = {} // 表单重置
        this.initConfig.province = [];
        this.data.lat = '';
        this.data.lng = '';
        this.data.addrss = '';
        this.initConfig.form.estate = '1'
        this.handleReset('form') // 验证重置
      },
      edit(row) {

        let obj = JSON.parse(JSON.stringify(row)) // 行数据

        this.initConfig.createModal = true
        this.initConfig.createTitle = '编辑'
        this.isAdd = false
        this.initConfig.province = [];
        this.data.lat = '';
        this.data.lng = '';
        this.data.addrss = '';
        this.initConfig.form = {} // 表单重置
        this.initConfig.form = obj;
        this.initConfig.form.estate = obj.estate.toString()
        this.initConfig.province = [obj.province_id,obj.city_id,obj.area_id];

        // 赋值接口返回
        this.handleReset('form') // 验证重置
      },
      // 删除
      del(row) {
        this.initConfig.delId = row.id
        this.initConfig.delModal = true
        // 删除接口
      },
      confirmDel() {

        let _this = this
        let obj = {
          id: this.initConfig.delId
        }
        deleteEnter(obj).then(res => {
          if (res.data.status == 1) {
            _this.initConfig.delModal = false
            _this.$Message.success('操作成功')
            _this.getList() // 重新刷新数据
          } else {
            _this.initConfig.delModal = false
            // axios响应拦截
          }
        }).catch(function(error) {
          // 异常
          _this.initConfig.delModal = false
          console.log(error)
        })
      },
      changepage(e) {
         this.initConfig.page.current = e;
        this.getList();
      },

      handleReset(name) {
        this.$refs[name].resetFields()
      },
      changeAreaData(value, selectedData) {
        this.initConfig.form.province_id = selectedData[0].value;
        this.initConfig.form.province_name = selectedData[0].label;
        this.initConfig.form.city_id = selectedData[1].value;
        this.initConfig.form.city_name = selectedData[1].label;
        this.initConfig.form.area_id = selectedData[2].value;
        this.initConfig.form.area_name = selectedData[2].label;

      },
      selectLocation() {
        if (!this.data.lat || !this.data.lng) {
          this.$Message.error('请选择经纬度')
          return
        }
        this.showMapModel = false
        this.initConfig.form.lat = this.data.lat;
        this.initConfig.form.lng = this.data.lng;
        this.initConfig.form.address =this.data.address
      },
      setMap() {
        let _this = this
        if (this.initConfig.form.address == '') {
          this.$Message.error('详细地址不能为空')
          return false
        }
        if (this.initConfig.province.length == 0 || !this.initConfig.form.address) {
          this.$Message.error('请选择省市区，并输入详细地址')
          return
        }

        let content = _this.initConfig.form.province_name + _this.initConfig.form.city_name + _this.initConfig.form
          .area_name +
          _this.initConfig.form.address
        // this.formItem.content = JSON.parse(JSON.stringify(content))
        this.keyword = JSON.parse(JSON.stringify(content))
        this.initMap()
        this.showMapModel = true
      },
      comfirmUpdateMap() {

      },
      cancelUpdateMap() {
        this.showMapModel = false;
      },
      //初始化地图
      initMap() {
        let _this = this;
        var map = new AMap.Map('container', {
          zoom: 10
        });
        AMapUI.loadUI(['misc/PoiPicker'], function(PoiPicker) {

          var poiPicker = new PoiPicker({
            input: 'searchInput',
            placeSearchOptions: {
              map: map,
              pageSize: 10
            },
            searchResultsContainer: 'searchResults'
          });

          poiPicker.on('poiPicked', function(poiResult) {
            poiPicker.hideSearchResults();
            var source = poiResult.source,
              poi = poiResult.item;
            if (source !== 'search') {
              //suggest来源的，同样调用搜索
              poiPicker.searchByKeyword(poi.name);
            } else {
              _this.data.lat = poi.location.lat
              _this.data.lng = poi.location.lng
              _this.data.address = poi.address+poi.name;

            }
            // $("#searchResults").toggleClass("hidden");

          });
          poiPicker.onCityReady(function() {
            poiPicker.searchByKeyword(_this.keyword);
          });
        });

      },

    }

  }
</script>

<style lang="scss">
  @import "./index";
</style>
